#include "test_discovery_meter.h"
#include "utils.h"
#include "discovery_meter.h"

#if DEBUG_SEARCH_VIRTUAL_METER

#define NONE_MATCH      (-1 )
#define COLLIDE_MATCH   (-2 )
const char meterNum2[][DISCOVERY_MAX_LAYER+1]=
{
    "8881234567",//no use
    "1810300180",
    "1810300021",
    "1810300141",
    "1810300091",
    "1810300052",
    "1810300053",
    "1810300056",
    "1810300148",
    "1810300149",
    "1810300089",
    "0000000009",
    "0000000010",
    "0000000011",
    "0000000012",
};

static int8_t compare_meter_addr(const char addr[], const unsigned char match[])
{
    int i;

    for(i = DISCOVERY_MAX_LAYER - 1; i >= 0 ; i--)
    {
        char start, end;
        start = (char)((match[i] >> 4)& 0x0F) + '0';//num to str
        end = (char)(match[i] & 0x0F) + '0';//num to str

        if((start <= addr[i]) && (addr[i]<= end))
        {
            continue; //compare next bit 
        }
        else
        {
            return -1;
        }
    }
    return 0;
}

uint8_t  cnt_09_in_wildcard_reverse(uint8_t str[])
{
    uint8_t cnt = 0;
    int i=0;
    for(i = DISCOVERY_MAX_LAYER - 1; i > 0; i--)
    {
        if(str[i] == 0x09)
            cnt++;
        else
            break;

    }
    return cnt;
}

int discovery_virtual_meter(uint8_t wildcard[],uint8_t addr[])
{
	   
    int i;
    int match_cnt = 0;
    int match_idx;
    for(i = 1; i < array_size(meterNum2); i++)
    {
        int8_t ret = compare_meter_addr(meterNum2[i], wildcard);
        if(0 == ret)
        {
            match_cnt++;
            match_idx = i;
        }
    }
	
    switch(match_cnt)
    {
        case 0: 
			return NONE_MATCH;
        case 1:
			put_le_val(match_idx, addr, sizeof(match_idx));
			return match_idx;
        default:
        	return COLLIDE_MATCH;
    }
}
#endif

#if DISCOVERY_DEBUG
uint8_t  cnt_09_in_wildcard(uint8_t str[])
{
    uint8_t cnt = 0;
    int i=0;
    for(i = 0; i < DISCOVERY_MAX_LAYER ; i++)
    {
        if(str[i] == 0x09)
            cnt++;
        else
            break;

    }
    return cnt;
}

#endif

